package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.model.enums.PaymentType;
import com.atguigu.gmall.model.payment.PaymentInfo;
import com.atguigu.gmall.payment.config.AlipayConfig;
import com.atguigu.gmall.payment.service.PaymentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/api/payment/alipay")
public class PaymentController {

    @Resource
    private PaymentService paymentService;

    @Resource
    private AlipayClient alipayClient;

    @GetMapping("/submit/{orderId}")
    @ResponseBody
    public String Submit(@PathVariable Long orderId){
        PaymentType paymentType = PaymentType.ALIPAY;
        //保存支付信息
        paymentService.savePaymentInfo(orderId,paymentType);
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId);
        //连接支付宝
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        Map map = new HashMap();
        map.put("out_trade_no",paymentInfo.getOutTradeNo());
        map.put("product_code","FAST_INSTANT_TRADE_PAY");
        map.put("total_amount",paymentInfo.getTotalAmount());
        map.put("subject",paymentInfo.getSubject());
        request.setBizContent(JSONObject.toJSONString(map));

        //设置同步地址
        request.setReturnUrl(AlipayConfig.return_payment_url);
        //设置异步地址
        request.setNotifyUrl(AlipayConfig.notify_payment_url);

        AlipayTradePagePayResponse response = null;
        try {
            response = alipayClient.pageExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
            System.out.println(response.getBody());
        } else {
            System.out.println("调用失败");
        }
        return response.getBody();
    }

    //同步回调
    @GetMapping("/callback/return")
    public String callbackReturn(){
        System.out.println("支付宝来过了" + AlipayConfig.return_order_url);
        return "redirect:" + AlipayConfig.return_order_url;
    }

    //异步通知
    @PostMapping("/callback/notify")
    public String callbackNotify(@RequestParam Map<String, String> paramsMap){
        //将异步通知中收到的所有参数都存放到map中
        System.out.println("post请求来了");
        try {
            //调用SDK验证签名
            boolean signVerified = AlipaySignature.rsaCheckV1(paramsMap,
                    AlipayConfig.alipay_public_key,
                    AlipayConfig.charset,
                    AlipayConfig.sign_type);
            if(signVerified){
                //验签成功后，按照支付结果异步通知中的描述，对支付结果中的业务内容进行二次校验，
                // 校验成功后在response中返回success并继续商户自身业务处理，校验失败返回failure
                String trade_status = paramsMap.get("trade_status");
                if (trade_status.equals("TRADE_SUCCESS")){
                    //用户已经支付了 并且金额也是正确的
                    //发MQ 1ms  最终一致性
                    //1:金额也是正确的
                    //2:更新支付信息表  银行流水  时间  内容
                    //3:更新订单状态 未支付改为已支付
                    //4:本项目没有使用  用户收到一优惠
                    //5:订单商品库存 扣减商品剩余库存
                    //用户级别  用户积分
                    paymentService.paySuccess(paramsMap);
                    return "success";
                } else {
                    //验签失败则记录异常日志，并在response中返回failure.
                    return "failure";
                }
            }
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "failure";
    }

    //退款
    //http://payment.gmall.com/api/payment/alipay/refund/ATGUIGU158348294514133
    @GetMapping("/refund/{outTradeNo}")
    @ResponseBody
    public Result refund(@PathVariable String outTradeNo){
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        Map map = new HashMap();
        BigDecimal refundAmount = paymentService.getRefundAmount(outTradeNo);
        map.put("refund_amount",refundAmount);
        map.put("out_trade_no",outTradeNo);
        request.setBizContent(JSONObject.toJSONString(map));
        AlipayTradeRefundResponse response = null;
        try {
            response = alipayClient.execute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        if(response.isSuccess()){
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return Result.ok();
    }

    //测试外网 域名的
    @ResponseBody
    @GetMapping("/index")
    public Result index(){
        return Result.ok();
    }
}
